local Toast = class("Toast",function() return display.newLayer("Toast") end)

Toast.parentNode = nil
Toast.runner = nil
Toast.enable = true
Toast.isCache = false
Toast.caches = nil

function Toast:ctor(text)
    self._isRunning = false
    self.mUINode = cc.CSLoader:createNode(Res.FloatNotifyBarUI)
    if cc.isDead(self) then
        return
    end
    self:addChild(self.mUINode)
    self.mUINode:setContentSize(cc.size(display.width,display.height))
    ccui.Helper:doLayout(self.mUINode)

    local groupNode = self.mUINode:getChildByName("group")
    local rootNode = groupNode:getChildByName("Clearing")
    local textContent = rootNode:getChildByName("Text")
    local bg = rootNode:getChildByName("bg")

    local str = text or ""
    textContent:setString(str)

    self._textContent = textContent
    self._bg = bg
    self._rootNode = rootNode

    local uiAction = cc.CSLoader:createTimeline(Res.FloatNotifyBarUI)
    self.mUINode:runAction(uiAction)
    self._action = uiAction
    self:setVisible(false)
end

function Toast:run(text)
    if self._textContent and self._action then
        self._isRunning = true
        self:setVisible(true)
        self._textContent:setString(text)
        local wd = self._textContent:getContentSize().width
        if wd >= 500 then
            display.setNodesMiddle(self._rootNode, self._bg, self._textContent)
        end
        local action = self._action
        action:gotoFrameAndPlay(0,action:getDuration(),false)
        action:setLastFrameCallFunc(function() 
            self._isRunning = false
            self:setVisible(false)
        end)
    end
end

function Toast:isRunning()
    return self._isRunning
end


local ToastRunner = class("ToastRunner",function() return display.newLayer("ToastRunner") end)

local MaxDisplay = 3
local PoolSize = 6

function ToastRunner:ctor()
    self.queue={}
    self.toastPool={}
    self:scheduleUpdate(handler(self,ToastRunner.run))
    self:setContentSize(cc.size(display.width,display.height))
    self:enableNodeEvents()
    self:initPool()
    self._lastTime = 0
end

function ToastRunner:initPool()
    for i=1,PoolSize do
        local t = Toast.new("")
        if cc.isAlive(t) then
            self:addChild(t)
            table.insert(self.toastPool,t)
        end
    end
end

function ToastRunner:getFreeToast()
    for _,v in ipairs(self.toastPool) do
        if not v:isRunning() then
            return v
        end
    end
end

function ToastRunner:onCleanup()
    self.queue={}
end

function ToastRunner:push(text, tag)
    table.insert(self.queue,{text = text, tag = tag or Enums.ToastTag.normal})
end

function ToastRunner:clearByTag(tag)
    local queue = {}
    for k,v in pairs(self.queue) do
        if v.tag ~= tag then
            table.insert(queue, v)
        end
    end
    self.queue = queue
    --dump(self.queue, "toast queue clear end", 6)
end

function ToastRunner:clearAll()
    self.queue = {}
end

function ToastRunner:run(dt)
    local curTime = app:getTime()
    local dt = curTime-self._lastTime
    if dt < 0.5 then
        return 
    end
    
    local top = self.queue[1]
    if top then
        local toast = self:getFreeToast()
        if toast then
            toast:run(top.text)
        end
        table.remove(self.queue,1)

        AM.playSoundById(2019)
        self._lastTime = curTime
    end
end

function Toast.setParentNode(node)
    if node then
        local runner = ToastRunner.new()
        node:addChild(runner)
        runner:setName("ToastRunner")
        Toast.runner = runner
    end
end

-- 可以设置Toast是否可用，不可用状态将忽略掉push数据
function Toast.setEnable(b)
    Toast.enable = b
end

-- 可以设置Toast是否cache，暂时缓存数据，解除cache再push所有数据
function Toast.setCache(b)
    Toast.isCache = b
    if b and Toast.caches then
        for i,v in ipairs(Toast.caches) do
            Toast.push(v.text, v.tag)
        end
        Toast.caches = nil
    end
end

function Toast.push(text, tag)
    local runner = Toast.runner
    if runner then
        if Toast.enable then
            runner:push(text, tag)
        elseif Toast.isCache then
            Toast.caches = Toast.caches or {}
            Toast.caches[#Toast.caches + 1] = {text=text, tag=tag}
        end
    end
end

function Toast.clearByTag(tag)
    local runner = Toast.runner
    if runner then
        runner:clearByTag(tag)

        if Toast.caches then
            local caches = {}
            for i,v in ipairs(Toast.caches) do
                if v.tag ~= tag then
                    table.insert(caches, v)
                end
            end
            Toast.caches = caches
        end
    end
end

function Toast.clearAll()
    local runner = Toast.runner
    if runner then
        runner:clearAll()
        Toast.caches = nil
    end
end

function Toast.setToastVisible(visible)
    if Toast.runner then
        Toast.runner:setVisible(visible)
    end
end

return Toast ,ToastRunner